#!/bin/bash

# 下载mongdb
# wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-4.0.13.tgz

## 解压
tar zxf mongodb-linux-x86_64-4.0.13.tgz
mv ./mongodb-linux-x86_64-4.0.13/ /usr/local/mongodb

## 创建全局链接
ln -s /usr/local/mongodb/bin/mongo /usr/local/bin/mongo
ln -s /usr/local/mongodb/bin/mongod /usr/local/bin/mongod

## mongodb 数据库配置
mkdir -p /data/db
mkdir -p /data/log

## 创建mongod.conf配置
echo "systemLog:
  destination: file
  logAppend: true
  path: /data/log/mongodb.log # 日志文件
storage:
  dbPath: /data/db  # 数据目录
  journal:
    enabled: true
processManagement:
  fork: true  # fork and run in background
  timeZoneInfo: /usr/share/zoneinfo
net:
  port: 27017      # 端口
  bindIp: 0.0.0.0 # 绑定IP" > /usr/local/mongodb/bin/mongod.conf

## 创建mongodb服务
echo "[Unit]

Description=mongodb 
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
ExecStart=/usr/local/mongodb/bin/mongod --config /usr/local/mongodb/bin/mongod.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/usr/local/mongodb/bin/mongod --shutdown --config /usr/local/mongodb/bin/mongod.conf
PrivateTmp=true

[Install]
WantedBy=multi-user.target" > /lib/systemd/system/mongodb.service

## 启动服务
mongod --dbpath /data/db --fork --logpath /data/log/mongodb.log

## 创建帐号
read -p "输入root账号密码:" password
mongo admin --eval "db.createUser({ user: 'root', pwd: '$password', roles: [ { role: 'root', db: 'admin' } , 'readWriteAnyDatabase'] })"

## 关闭 mongodb 服务
ID=`ps -ef | grep "mongod" | grep -v "grep" | awk '{print $2}'`
for id in $ID
do
    if [ "$BASHPID" -ne "$id" ]
    then
        kill -9 $id  &>/dev/null
    fi
done

## 服务启动
systemctl start mongodb.service
#开机启动
systemctl enable mongodb.service
